package icu.groot.alan.servlet.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.groot.alan.entity.*;
import icu.groot.alan.service.DepartmentService;
import icu.groot.alan.service.UserService;
import icu.groot.alan.service.impl.DepartmentServiceImpl;
import icu.groot.alan.service.impl.UserServiceImpl;
import icu.groot.alan.util.R;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/list.do")
public class UserListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNow = req.getParameter("pageNow");
        String pageSize = req.getParameter("pageSize");
        String fuzzyQuery = req.getParameter("fuzzyQuery");
        String department = req.getParameter("department");

        ObjectMapper objectMapper = new ObjectMapper();
        if (StringUtils.isAnyBlank(pageSize, pageNow)){
            resp.getWriter().print(objectMapper.writeValueAsString(R.error("参数缺失")));
            return;
        }
        UserService userService = new UserServiceImpl();
        Paging<OneselfUser> paging = new Paging<>();
        int departmentId = 0;
        try {
            paging.setPageSize(Integer.parseInt(pageSize));
            paging.setPageNow(Integer.parseInt(pageNow));
            paging.setFuzzyQuery(fuzzyQuery);
            paging.setDepartmentId(Integer.parseInt(department));
        }catch (Exception e){
            e.printStackTrace();
            resp.getWriter().print(objectMapper.writeValueAsString(R.error("参数格式错误")));
            return;
        }
        userService.paging(paging);
        DepartmentService departmentService = new DepartmentServiceImpl();
        List<Department> departments = departmentService.getDepAll();
        req.getSession().setAttribute("paging", paging);
        req.getSession().setAttribute("navActive", "navUser");
        req.getSession().setAttribute("departments", departments);
        req.getSession().setAttribute("identity", ((TokenEntity) req.getAttribute("tokenEntity")).getDepartment());
        req.getRequestDispatcher("/user-list.jsp").forward(req,resp);
    }
}
